import time
import requests
from Common.handle_redis import RedisHelper
from Common.connect_to_device import *
from Common.hande_device import HandleDevices
from influxdb_client import Point
from Common.handle_influxdb import InfluxDBHandler

do_redis = RedisHelper(host="10.10.118.92", port="6379", password="li123456")
# DINGTALK_WEBHOOK = "https://oapi.dingtalk.com/robot/send?access_token=22dd0dacb7476ca49c51a9cf121b2850f2519cbda2df44e6af8f1ffeae76aad3"
DINGTALK_WEBHOOK = "https://oapi.dingtalk.com/robot/send?access_token=b1d7e64d33609f88d5c88ae23e43d28b0bd40dd2d6a896d43449c90415cff4cf"
do_devices = HandleDevices(CPDemo_pkgName=MID_pkgName)
do_influxdb = InfluxDBHandler()
# continue_chllect = False
# 初始化变量，保存上一次的pid值
last_pid_main_cpdemo = None
last_pid_sec_cpdemo = None

while True:
    try:
        apm_pid_main, apm_pid_sec, pid_main_cpdemo, pid_sec_cpdemo = do_devices.handle_main_device(
            deviceId_001=device_1)
        print(f"当前主屏PID为:{pid_main_cpdemo}")
        print(f"当前副屏PID为:{pid_sec_cpdemo}")
        # 如果是第一次循环，初始化last_pid_main_cpdemo和last_pid_sec_cpdemo
        if last_pid_main_cpdemo is None and last_pid_sec_cpdemo is None:
            last_pid_main_cpdemo = pid_main_cpdemo
            last_pid_sec_cpdemo = pid_sec_cpdemo

        # 检查当前的pid值是否与上一次不同
        elif pid_main_cpdemo != last_pid_main_cpdemo or pid_sec_cpdemo != last_pid_sec_cpdemo:
            print("PID值发生变化，停止循环。")
            break  # 退出循环

        time.sleep(2)

        # 获取CPU和内存数据
        device_001_main_cpu = do_devices.get_cpu(apm_pid_main)["appCpuRate"]
        device_001_main_mem = do_devices.get_mem(apm_pid_main)
        device_001_sec_cpu = do_devices.get_cpu(apm_pid_sec)["appCpuRate"]
        device_001_sec_mem = do_devices.get_mem(apm_pid_sec)
        print(f"主屏数据:{device_001_main_cpu} {device_001_main_mem}")
        print(f"副屏数据:{device_001_sec_cpu} {device_001_sec_mem}")
        # 准备数据点列表
        measurements = [
            Point("device_001").tag("pid", "main_pid").field("cpu", device_001_main_cpu),
            Point("device_001").tag("pid", "main_pid").field("mem", device_001_main_mem),

            # 分割
            Point("device_001").tag("pid", "sec_pid").field("cpu", device_001_sec_cpu),
            Point("device_001").tag("pid", "sec_pid").field("mem", device_001_sec_mem)
        ]

        # 写入数据库
        do_influxdb.write_mul_data(measurements=measurements)

        # 更新上一次的pid值
        last_pid_main_cpdemo = pid_main_cpdemo
        last_pid_sec_cpdemo = pid_sec_cpdemo

    except Exception as e:
        print(f"发生错误: {e}")
        try:
            # requests.get(url="https://api.day.app/s3KoLFVvWVWdYiiro2gKW/A1性能采集可能出现问题")
            do_redis.set(key="stop_DP_single", value="True", ex="86400")
            break
        except:
            pass
# 中断循环后发送钉钉通知
do_redis.set(key="stop_DP_single", value="True", ex="86400")


# if pid_main_cpdemo != last_pid_main_cpdemo:
#     if pid_sec_cpdemo != last_pid_sec_cpdemo:
#         crash_info = "主端和从端都可能crash"
#     else:
#         crash_info = "主端可能crash"
# elif pid_sec_cpdemo != last_pid_sec_cpdemo:
#     crash_info = "从端可能crash"
# else:
#     crash_info = "未知错误"
message = {
    "msgtype": "text",
    "text": {
        "content": (
            # "多屏性能测试\n"
            # "【洛科台架】多屏PID变动，请及时查看。"
            "🚨 **多屏性能测试** 🚨\n"  # 使用表情符号和加星号的方式来强调标题
            "📌 **【洛轲台架】多屏PID变动，请及时查看**"  # 使用表情符号和加星号的方式来强调内容
        )
    },
    "at": {
        "atMobiles": [
            # "15658026027",  # 替换为要@的人的手机号
            "18767091896",  # 替换为要@的人的手机号
        ],
        "isAtAll": False  # 如果要@所有人，这里改为 True
    }
}

headers = {
    'Content-Type': 'application/json'
}
response=requests.post(DINGTALK_WEBHOOK, json=message)
print(response.json())
# 面板地址
# http://10.10.118.92:3000/d/XLeMAXqIz/dp-dan-bo?orgId=1
# adb shell am start com.arcvideo.sdk.demo/com.arcvideo.ivi.sdk.demo2.activity.UnicastActivity
# adb shell am start --user 999 --display 2 com.arcvideo.sdk.demo/com.arcvideo.ivi.sdk.demo2.activity.UnicastActivity
# adb shell am force-stop com.arcvideo.sdk.demo